package com.zlsy.thread.atomic;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author zhouliang
 * @date 2020/8/12 19:21
 * 在高并发场景下LongAdder比AtomicLong效率高
 */
public class LongAdderDemo {

    public static void main(String[] args) throws InterruptedException {
        LongAdder atomic = new LongAdder();
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        TaskLong task = new TaskLong(atomic);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            executorService.execute(task);
        }
        long endTime = System.currentTimeMillis();
        executorService.shutdown();

        //executorService是否停止了
        while (!executorService.isTerminated()) {
            //不停止就一直while
        }
        System.out.println(String.format("cost time:%s,result:%s", endTime - startTime, atomic.sum()));
    }
}

class TaskLong implements Runnable {

    private LongAdder atomic;

    public TaskLong(LongAdder atomic) {
        this.atomic = atomic;
    }


    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            atomic.increment();
        }
    }
}
